import re
from get_net import GetNet

class GetWebSite2():
    def __init__(self, current_data:dict={}):
        self.cookies = ""
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0",
            "Cookie": self.cookies
        }
        self.post_data = {
            "step": "2",
            "keyword": "keyword", # 關鍵詞
            "method": "AND", # "OR"部分匹配關鍵詞 "AND"完全匹配關鍵詞
            "pwuser": "",
            "sch_area": "0",
            "f_fid": "all",
            "sch_time": "all", # 搜索時間範圍 all即所有
            "orderway": "postdate",
            "asc": "DESC"
        }
        self.current_data = current_data

    def identify(self, html) -> int:
        """傳入WebSite2的html 通過正則表達式獲取搜索結果數並返回 獲取失敗返回-1"""
        result = re.findall(r"共搜索到了([0-9]*)条信息",html)
        result = int(result[0]) if len(result) > 0 else -1
        return result

    def get_page(self, url: str, post: dict) -> str:
        """請求鏈接 返回提示錯誤的文本 或者response.text"""
        downloader = GetNet(self.headers)
        response = downloader.post(url,post)
        response = response if isinstance(response, str) else response.text
        return response

    def get_result(self):
        """獲取WebSite2的搜索數據"""
        main_url = "https://www.webSite2.net/search.php"
        new_data = {}
        post_data = self.post_data
        for key in self.current_data:
            print("Getting from WebSite2 which keyword is " + key + ":")
            post_data["keyword"] = key
            html = self.get_page(main_url, post_data)
            new_result = self.identify(html)
            new_data[key] = new_result
        return new_data
    
    def compare_data(self, new_data:dict) -> bool:
        """對比新舊數據 視情況補充"""
        pass

def test():
    WebSite2_data = {"test":0}
    downloader = GetWebSite2(WebSite2_data)
    print(downloader.get_result())

if __name__ == "__main__":
    test()